'use strict';

const db = uniCloud.database();
const dbCmd = db.command 

exports.main = async (event, context) => {
	
	const collection = db.collection(event.database);

	if(event.methedName =="list"){
		let limit=event.limit || 10000;
		let filter=event.filter ||{}
		let orderField=event.orderFiled
		let orderType=event.orderType
		if(orderField){
			const res = await collection.where(filter).limit(limit).orderBy(orderField,orderType).get()
		    return res;
		}else{
			const res = await collection.where(filter).limit(limit).get()
		    return res;
		}
		
	}
	
	if(event.methedName=="count"){
		let res = await db.collection('goods').where({
		  _db: dbCmd.exists(true)
		}).count();
		return res;
	}
	
	if(event.methedName=="add"){
		const res = await collection.add(event.data)
		return res
	}
	
	
	if(event.methedName=="delete"){
		let filter=event.filter
		if(!filter){
			let res = await collection.get()	
			for(let i=0;i<res.data.length;i++){
				let docu=res.data[i];
				let id=docu._id;
				console.log("hezhiq",id)
				await collection.doc(id).remove();
			}
			return {"code":0}
		}
		if(filter._id){
			 return await collection.doc(filter._id).remove();
		}else{
			return await collection.where(filter).remove()
		}
	}

	if(event.methedName=="update"){
		let id=event.data._id;
		delete event.data._id;
		const res = await collection.doc(id).update(event.data);
		return res
	}
	
  return event
};
